package com.awesome.activitydemo.utils;

import android.app.Activity;
import android.app.Application;
import android.os.Bundle;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;

import com.awesome.common.util.log.ShowLogUtil;

/**
 * Author: zhangjingfang
 * Email:zhangjingfang@jeejio.com
 * Date: 2022/3/10
 * Description:类描述
 */
public class ActLifecycle implements Application.ActivityLifecycleCallbacks {
    private int activityStartedCount = 0;
    // 是否在前台，true前台，false后台
    private boolean isFore = false;
    private onForeListener mOnForeListener;


    @Override
    public void onActivityCreated(@NonNull Activity activity, @Nullable Bundle savedInstanceState) {
        ShowLogUtil.info("onActivityCreated");
        ActivityManager.addActivity(activity);
    }

    @Override
    public void onActivityStarted(@NonNull Activity activity) {
        ShowLogUtil.info("onActivityStarted");
        activityStartedCount++;
        if (activityStartedCount == 1 && !isFore) {
            ShowLogUtil.info("应用进入前台");
            isFore = true;
            mOnForeListener.onFore(true);
        }
    }

    @Override
    public void onActivityResumed(@NonNull Activity activity) {
        ShowLogUtil.info("onActivityResumed");

    }

    @Override
    public void onActivityPaused(@NonNull Activity activity) {
        ShowLogUtil.info("onActivityPaused");

    }

    @Override
    public void onActivityStopped(@NonNull Activity activity) {
        ShowLogUtil.info("onActivityStopped");
        activityStartedCount--;
        if (activityStartedCount <= 0 && isFore) {
            ShowLogUtil.info("应用进入后台");
            isFore = false;
            mOnForeListener.onFore(false);
        }
    }

    @Override
    public void onActivitySaveInstanceState(@NonNull Activity activity, @NonNull Bundle outState) {
        ShowLogUtil.info("onActivitySaveInstanceState");
    }

    @Override
    public void onActivityDestroyed(@NonNull Activity activity) {
        ShowLogUtil.info("onActivityDestroyed");
        ActivityManager.removeActivity(activity);
    }

    public void setOnForeListener(onForeListener listener) {
        mOnForeListener = listener;
    }

    public interface onForeListener {
        void onFore(boolean isFore);
    }
}
 
 